package com.twu.biblioteca.controller;

import com.twu.biblioteca.BibliotecaApp;
import com.twu.biblioteca.DAO.BookDAO;
import com.twu.biblioteca.model.Book;
import com.twu.biblioteca.view.BookListView;

import java.util.Scanner;

/**
 * Created by andreas on 21.04.14.
 */
public class BookListController extends AbstractController implements Controller {

    private final BookDAO bookDAO;
    private final BookListView bookListView;

    public BookListController(Scanner reader, BibliotecaApp app) {
        super(reader, app);

        bookListView = new BookListView();
        bookDAO = app.getBookDAO();

        println("Please find a list with all available books below.\n");
        println(bookListView.render(bookDAO.findAvailableBooks()));
        printCheckoutInstructions();

        handleUserInput();
    }

    void printCheckoutInstructions() {
        println("");
        println("[ID] Enter the ID of the book you want to checkout\n" +
                "[Back] Go back to the main menu\n" +
                "[Quit] quit");
        println("");
    }

    private void printConfirmationMessage() {
        println("");
        println("Thank you! Enjoy the book");
        println("");
    }

    private void printUnavailableMessage() {
        println("");
        println("That book is not available.");
        println("");
    }

    @Override
    public void doHandleUserInput(String input) {
        switch (input) {
            case "Back":
                goTo(Place.MAIN_MENU);
                break;
            case "Quit":
                handleUserInput = false;
                println("Have a nice day!");
                break;
            default:
                if (input.matches("[0-9]+")) {
                    Book book = bookDAO.find(new Integer(input));
                    if (book != null) {
                        if (book.isReserved()) {
                            printUnavailableMessage();
                            goTo(Place.BOOK_LIST);
                        } else {
                            reserveBook(book);
                            printConfirmationMessage();
                            goTo(Place.BOOK_LIST);
                        }

                        return;
                    }
                }
                println("Select a valid option!\n");
        }
    }

    private void reserveBook(Book book) {
        book.setReserved(true);
    }
}
